package org.example.core.storage.controller;

import org.example.common.utils.ResponseUtil;
import org.example.core.storage.service.StorageService;
import org.example.db.entity.ObjectStorage;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/storage")
public class StorageController {

    StorageService storageService;

    public StorageController(StorageService storageService) {
        this.storageService = storageService;
    }

    @PostMapping("/upload")
    public Object upload(@RequestBody MultipartFile file) throws IOException {

        if(file == null){
            return ResponseUtil.badArgument();
        }
        ObjectStorage store = storageService.store(file.getInputStream(), file.getSize(), file.getContentType(), file.getOriginalFilename());
        return ResponseUtil.ok(store);
    }

    @GetMapping("/fetch/{key:.+}")
    public ResponseEntity<Resource> fetch(@PathVariable String key) {
        ObjectStorage objectStorage = storageService.findByKey(key);
        if (key == null) {
            return ResponseEntity.notFound().build();
        }
        if (key.contains("../")) {
            return ResponseEntity.badRequest().build();
        }
        String type = objectStorage.getType();
        MediaType mediaType = MediaType.parseMediaType(type);

        Resource file = storageService.loadAsResource(key);
        if (file == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok().contentType(mediaType).body(file);
    }

}
